import React, { PureComponent } from 'react';
import '@ant-design/compatible/assets/index.css';
import { Card, Table, Button, Modal, message, Row } from 'antd';
import { connect } from 'dva';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import Ellipsis from '../../../components/Ellipsis';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import { filterAuth } from '@/support/common';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import router from 'umi/router';
import moment from 'moment';
import { getDicByKey, findDicByCodeSort } from '@/support/common';
import PropTypes from 'prop-types';
import { getDataByCode } from '@/components/common/PateoForm/utils/helper';
import { getMd5, getKeyValueString } from '@/utils/utils';
import { getToken } from '../../../components/common/PateoForm/utils/helper';
import { fingerprintFetch } from '@/utils/request';

let pageObj = {};
let strategyMap = new Map();
strategyMap.set(1,'需购买且赠送');
strategyMap.set(2,'需购买且试用');
strategyMap.set(3,'需购买但不赠送不试用');
strategyMap.set(4,'不需要购买');

const mapStateToProps = (state: any) => ({
  bluetoothConfiguration: state.bluetoothConfiguration,
  loading: state.loading.models['bluetoothConfiguration'],
   menu: state.menu,
});
class BluetoothConfiguration  extends PureComponent<any, any> {
  static contextTypes = {
    authButton: PropTypes.array,
    dicData: PropTypes.any,
  };
  state = {
    formValues: {},
    formData: {},
    pageData: {
      curPage: 1,
      pageSize: 10,
    },
    seriesOptions: [], // 车系
    nameOptions: [], //车型组
    redisData: {},
  };

  componentDidMount() {
    // 获取车系数据
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'bluetoothConfiguration/getDataWithRes',
      payload: { url: '/msdevice/base/vehicle/series/list' },
      callback: (e: any) => {
        if (e.data) {
          this.setState({
            seriesOptions: e.data.map((e:any) => ({
              label: e.seriesName,
              value: e.seriesCode,
            })),
          });
        }
      },
    });
    this.props.dispatch({
      type: 'basedata/redisDataFetch',
      callback: (response:any) => {
        if (response) {
          this.setState({ redisData: response });
        }
      },
    });
    this.getList();
  }
  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'bluetoothConfiguration/initData',
    });
  }
  getList() {
    const { dispatch } = this.props;
    const { formValues, pageData } = this.state;
    dispatch({
      type: 'bluetoothConfiguration/getFetchPage',
      payload: { url: '/bluetoothkey/tas/config/page', ...formValues },
    });
  }
  handleFormReset = () => {
    this.searchForm.current.setFieldsValue({});
    this.setState({
      nameOptions: [],
    });
  };

  handleTableChange = (pagination: any, filters: any) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const { current, pageSize } = pagination;
    this.setState({ pagination });
    const params = {
      curPage: current,
      pageSize: pageSize,
      ...formValues,
      ...filters,
    };
    dispatch({
      type: 'bluetoothConfiguration/getFetchPage',
      payload: { url: '/bluetoothkey/tas/config/page', ...params },
    });
  };
  postDelete = (record: any) => {
    const { dispatch } = this.props;
    let idList =[];
    idList = record.strategyConfigList.map((item:any)=>{
      return item.id
    })
    dispatch({
      type: 'bluetoothConfiguration/postListList',
      payload: { url: '/bluetoothkey/tas/config/delete', list: idList},
      callback: (res: any) => {
        if (res.statusCode === '0') {
          message.success('删除成功！');
          this.getList();
        } else {
          // message.error(res.statusMessage);
        }
      },
    });
  };
  // 通过车系查询车型组
  onSerieSelect = (value: any) => {
    if (value) {
      this.props.dispatch({
        type: 'bluetoothConfiguration/postData',
        payload: { url: '/vehicle/group/findBySeriesCode', seriesCode: value },
        callback: (e: any) => {
          if (e.data) {
            this.setState({
              nameOptions: e.data.map(e => ({
                label: e.name,
                value: e.code,
              })),
            });
          } else {
            this.setState({
              nameOptions: [],
            });
          }
        },
      });
    } else {
      this.setState({
        nameOptions: [],
      });
    }
    this.searchForm.current.setFieldsValue({
      typeGroupCode: '',
    });
  };
  // 导出数据
  handleExportExcel = (record:any) => {
    let idList =[];
    idList = record.strategyConfigList.map((item:any)=>{
      return item.id
    })
    const param ={data: idList};
    const t =  { ...param};
    const str = `${window.g.url}/bluetoothkey/tas/config/exportList`;
    const newOptions: any = {};
    const obj = Object.assign({}, t);
    let dataStr = JSON.stringify(obj.data);
    let md5 = getMd5(dataStr)
    newOptions.method = 'POST';
    newOptions.body = dataStr;
    newOptions.headers = {
      Accept: 'application/json',
      OptAuthorization: `${getToken()}`,
      shaSign: md5,
      'Content-Type': 'application/json;charset=utf-8',
    };
    this.setState({
      exportLoading: true,
    });
    fingerprintFetch(str, newOptions)
      .then(response => {
        this.setState({
          exportLoading: false,
        });
        if (response.status === 200) {
          return response.blob();
        } else {
          throw response;
        }
      })
      .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `蓝牙钥匙报表-${new Date().toLocaleDateString()}.xls`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
      })
      .catch(() => {
        this.setState({
          exportLoading: false,
        });
        message.error('导出失败，请稍后再试!');
      });
  };

  render() {
    const {
      bluetoothConfiguration: {
        pageData: { strategyConfigList, curPage, pageSize,totalRows},
      },
      loading,
      location: { pathname = '/' },
      menu: { permissions, dicData },
    } = this.props;
    const { seriesOptions, nameOptions } = this.state;
    const pagination = {
      current: curPage,
      pageSize: pageSize,
      total: totalRows,
    }
    pageObj = pagination;
    const columns = [
      {
        title: '车系',
        dataIndex: 'seriesCode',
        render: (text:any) => {
          if (text) {
            return getDataByCode(this.state.redisData, 'vehicleSeriesList', text) || text;
          } else {
            return text;
          }
        },
      },
      {
        title: '车型组',
        dataIndex: 'typeGroupName',
        render: (text: any) => {
          return (
            <Ellipsis length={10} tooltip>
              {text}
            </Ellipsis>
          );
        },
      },
      {
        title: '蓝牙钥匙供应商',
        dataIndex: 'bluetoothProvider',
        render: (text:any) => {
          return getDicByKey(this.context.dicData, 'bluetoothProvider', text) || ''
        }
      },
      {
        title: '蓝牙服务配置下发',
        dataIndex: 'isBluetoothConfigSend',
        render: (text:any) => {
          if(text == 1){
            return '是'
          }else {
            return '否'
          }
        }
      },
      {
        title: '蓝牙运营策略',
        dataIndex: '',
        render: (text:any, record:any) => {
           if(record.strategyConfigList){
              return(
                <div>
                  {
                   record.strategyConfigList.map((item:any)=>{
                    return ( <Row>{getDicByKey(this.context.dicData, 'giveType', item.giveType)}{strategyMap.get(item.strategy)}{item.days? item.days+'天': ''}</Row>)
                })
                  }
                </div>
              )  
           }else{//未配置
            return "未配置";
           }
        },
      },
      {
        title: '蓝牙钥匙激活数',
        dataIndex: '',
        render: (text:any, record:any) => {
          if(record.strategyConfigList){//已配置 展示激活数量“3+下载报表
            let num=(record.strategyConfigList).reduce((pre:any,cur:any)=>{
              return pre+cur.activeNum
          },0)
            return (
              <div>
                <Row>{num}</Row>
                <Row><a onClick={()=>{this.handleExportExcel(record)}}>下载报表</a></Row>
              </div>
            );
          }else{//未配置  展示“0+下载报表
            return (
            <div>
                <Row>0</Row>
                <Row><a onClick={()=>{this.handleExportExcel(record)}}>下载报表</a></Row>
              </div>
            )
          }
        },
      },
      {
        title: '备注',
        dataIndex: 'remark',
        render: (text: any) => {
          return (
            <Ellipsis length={10} tooltip>
              {text}
            </Ellipsis>
          );
        },
      },
      {
        title: '操作人',
        dataIndex: 'updateBy',
      },
      {
        title: '创建时间',
        dataIndex: 'updateTime',
        render: (text: any) => {
          if (text) {
            return moment(text).format('YYYY-MM-DD HH:mm:ss');
          }
        },
      },
      {
        title: '操作',
        dataIndex: '操作',
        fixed: 'right',
        align: 'center',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '编辑',
              key: 'edit',
              auth: 'bluetoothConfiguration_edit',
              onConfirm: () => handleAdd(record),
            },
            {
              title: '删除',
              key: 'del',
              auth: 'bluetoothConfiguration_delete',
              onConfirm: () => {
                let confirmLoading = false;
                Modal.confirm({
                  title: '删除',
                  content: (
                    <>
                      <p>确定要删除当前蓝牙运营策略配置吗？</p>
                    </>
                  ),
                  wrapClassName: 'layer-model-box',
                  icon: <ExclamationCircleOutlined />,
                  onOk: close => {
                    // 如果为重复点击
                    if (confirmLoading) {
                      return false;
                    }
                    confirmLoading = true;
                    // 点击删除请求接口
                    this.postDelete(record);
                    // 刷新数据
                    this.getList();
                    // 关闭弹层
                    close();
                  },
                });
              },
            },
          ];
          return <PateoAuthButtons btns={btns} max={2} pathname={pathname} />;
        },
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };

    const searchItems = [
      {
        title: '车系',
        type: 'select',
        selectOptions: seriesOptions,
        key: 'seriesCode',
        onSelectChange: this.onSerieSelect,
      },
      {
        title: '车型组',
        type: 'select',
        selectOptions: nameOptions,
        key: 'typeGroupCode',
      },
    ];
    const  handleAdd = (record: any) => {
      const {menu: { dicData },} = this.props;
      const giveTypeList = findDicByCodeSort(dicData, 'giveType');
      const giveType = giveTypeList.map((item:any) =>{
        return ({
          giveType: item.dictKey,
          giveTypeName: item.dictValue
        })
      })
      const { formValues } = this.state;
      if (record) {
        sessionStorage.setItem('bluetoothConfiguration', JSON.stringify(record));
        router.push({
          pathname: '/remoteConfiguration/bluetoothConfiguration/bluetoothConfigurationEdit',
          state: { pageObj: pageObj, formValues, formData: record, giveType: giveType, backUrl: '/remoteConfiguration/bluetoothConfiguration' },
        });
      } else {
        sessionStorage.setItem('bluetoothConfiguration', '');
        router.push({
          pathname: '/remoteConfiguration/bluetoothConfiguration/bluetoothConfigurationAdd',
          state: { pageObj: pageObj, formValues, formData: {}, giveType: giveType,  backUrl: '/remoteConfiguration/bluetoothConfiguration' },
        });
      }
    };
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{
              type: 'bluetoothConfiguration/getFetchPage',
              url: '/bluetoothkey/tas/config/page',
              extraArgs: {},
            }}
            saveFormValues={(val: any) =>
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              })
            }
            handleFormReset={this.handleFormReset}
          />
        </Card>
        <Card style={{ marginTop: 12 }} bordered={false}>
          {filterAuth('bluetoothConfiguration_add', permissions, pathname) ? (
            <div className="my_newItem">
              <Button
                size="small"
                icon={<PlusOutlined />}
                type="primary"
                onClick={() => handleAdd()}
              >
                新增蓝牙运营策略
              </Button>
            </div>
          ) : null}
          <Table
            size={'small'}
            rowKey={record => record.groupTypeCode}
            dataSource={strategyConfigList}
            loading={loading}
            columns={columns}
            pagination={paginationProps}
            onChange={this.handleTableChange}
            scroll={{ x: 'max-content' }}
          />
        </Card>
      </div>
    );
  }
}

export default connect(mapStateToProps)(BluetoothConfiguration);
